import sqlalchemy
from flask import Blueprint, request, render_template, session, redirect
from app.models.UserModel import UserModel
from app.services import *
import time, hashlib

user = Blueprint('user', __name__, url_prefix='/user')


@user.before_request
def before_auth():
    passRule = ['/user/login', '/user/register', '/user/forget']
    from_url = request.headers.get('Referer', '/')
    if request.path in passRule:
        ...
    else:
        if not UserAuth.isLogin():
            jump_path = '?from={url}'.format(url=from_url)
            if from_url == '/':
                return redirect('/user/login' + jump_path)
            else:
                return redirect('/user/login')


@user.route('/login', methods=['POST', 'GET'])
def user_login():
    rm = request.method
    params = Utils.getParams(request)
    if rm == 'GET':
        return render_template('user/login.html')
    elif rm == 'POST':
        if all([params.get('username', False), params.get('password', False)]) is False:
            return m.error(message='缺少必要参数')
        filed = ['id', 'username', 'password', 'status', 'name', 'isadmin']
        filters = {UserModel.username == params.get('username')}
        try:
            rows = UserModel.getUser(filters=filters, field=filed)
        except sqlalchemy.exc.OperationalError:
            return m.error(message='服务器错误，登录失败！')
        if rows is None:
            return m.error(message='用户不存在')
        elif rows['password'] != Utils.md5hash(params['password']):
            return m.error(message='密码错误!')
        elif rows['status'] != 1:
            return m.error(message='账号被禁止登录!')
        else:
            data = {
                'logintime': int(time.time()),
                'loginip': request.remote_addr
            }
            try:
                session['userinfo'] = {
                    'username': rows['username'],
                    'name': rows['name'],
                    'isadmin': rows['isadmin']
                }
            except KeyError as err:
                return m.error(0, '用户状态异常，登录失败！')
            except session as err:
                return m.error(0, '服务器异常！请稍后再试！')
            status = UserModel.updateUser(filters=filters, data=data)
            return m.success(0, '登录成功！即将跳转...', {'data': rows, 'status': status})
    else:
        return 'Bad Request Methods'


@user.route('/register', methods=['GET', 'POST'])
def user_register():
    rm = request.method
    if rm == 'GET':
        return render_template('user/reg.html')
    elif rm == 'POST':
        params = Utils.getParams(request)
        username = params.get('username')
        password = params.get('password')
        nickname = params.get('nickname')
        if all([username, password, nickname]) is False:
            return m.error(0, '缺少必要参数！')
        else:
            filters = {
                UserModel.username == username
            }
            rows = UserModel.getUser(filters=filters)
            if rows:
                return m.error(message='用户已存在')
            else:
                data = {
                    'username': username,
                    'password': password,
                    'name': nickname,
                    'regip': request.remote_addr,
                    'isadmin': 0,
                    'regtime': int(time.time())
                }
                rows = UserModel.addUser(data)
                return m.success(message='ok', data=rows)
    else:
        return 'error'


@user.route('/info', methods=['GET', 'POST'])
def user_info():
    return jsonify(session.get('userinfo'))


@user.route('/messagebox', methods=['GET'])
def user_messagebox():
    rm = request.method
    if rm == 'GET':
        return render_template('app/message/index.html')
    elif rm == 'POST':
        return 'POST'
    else:
        return 'error'


@user.route('/logout', methods=['GET', 'POST'])
def user_logout():
    try:
        del session['userinfo']
    except KeyError as err:
        pass
    finally:
        return m.success(0, '操作成功')


@user.route('/forget', methods=['GET', 'POST'])
def user_forget():
    rm = request.method
    if rm == 'GET':
        return render_template('user/forget.html')
    elif rm == 'POST':
        return 'POST'
    else:
        return 'error'


@user.route('/getObjUsers', methods=['GET'])
def getObjUsers():
    rows = UserModel.getAllUser(filters={}, field=('id', 'name',))
    return m(code=0, count=len(rows),data=rows)


class Utils:

    @staticmethod
    def getParams(req):
        params = req.json or req.form or req.args or {}
        return params

    @staticmethod
    def md5hash(text):
        md5_org = hashlib.md5()
        md5_org.update(text.encode())
        return md5_org.hexdigest()
